
function addLoadEvent(func){
	var oldonload=window.onload;
	if(typeof window.onload !='function'){
		window.onload=func;
	}else{
		window.onload = function(){
			oldonload();
			func();
		};
	}
}

function insertAfter(newElement,targetElement){
	
	var parent = targetElement.parentNode;
	if(parent.lastChild == targetElement){
		parent.appendChild(newElement);
	}else{
		parent.insertBefore(newElement,targetElement.nextSibling);
	}
}

function addClass(element,value){
	if(!element.className){
		element.className=value;
	}else{
		newClassName=element.className;
		newClassName+=" ";
		newClassName+=value;
		element.className=newClassName;
	}
}

function highlightPage(){
	if(!document.getElementsByTagName) return false;
	if(!document.getElementById) return false;
    
	var headers =document.getElementsByTagName('header');
	if(headers.length == 0) return false;
	
	var navs= headers[0].getElementsByTagName('nav');
	if(navs.length == 0) return false;
	
	var links = navs[0].getElementsByTagName('a');
	for(var i=0;i<links.length;i++){
	 var linkurl;
	 for(var i=0;i<links.length;i++){
		 linkurl=links[i].getAttribute("href");
		 if(window.location.href.indexOf(linkurl)!= -1){
			 links[i].className="here";
			 var linktext= links[i].lastChild.nodeValue.toLowerCase();
			 document.body.setAttribute("id", linktext);
		 }
	 }
	}


}

addLoadEvent(highlightPage);


function prepareSlideshow(){
	if(!document.getElementById) return false;
	if(!document.getElementsByTagName) return false;
	
	if(!document.getElementById("intro")) return false;
	
	var intro= document.getElementById("intro");
	var slideshow =document.createElement("div");
	slideshow.setAttribute("id","slideshow");
	var preview=document.createElement("img");
	preview.setAttribute("src", "/JSDomDemo/images/slideshow.JPG");
	preview.setAttribute("alt", "a glimpse of what awaits you");
	preview.setAttribute("id", "preview");
	slideshow.appendChild(preview);
	insertAfter(slideshow,intro);
	
	var links = intro.getElementsByTagName("a");
	var destination;
	for(var i=0;i<links.length;i++){
		links[i].onmouseover = function(){
			destination = this.getAttribute("href");
			if(destination.indexOf("index.jsp") != -1){
				moveElement("preview",0,0,5);
			}
			if(destination.indexOf("life.jsp") != -1){
				moveElement("preview",-150,0,5);
				//document.getElementById("preview").style.left="150px";
			}
			if(destination.indexOf("study.jsp") != -1){
				moveElement("preview",-300,0,5);
				//document.getElementById("preview").style.left="-300px";
			}
			
		};
	}
}

 addLoadEvent(prepareSlideshow);

 function moveElement(elementID,final_x,final_y,interval){
		if(!document.getElementById)return false;
		if(!document.getElementById(elementID)) return false;
		var elem= document.getElementById(elementID);
		if(elem.movement){
			clearTimeout(elem.movement);
		}
		elem.style.position="relatvie";
		
		if(!elem.style.left){
			elem.style.left = "0px";
		}
		if(!elem.style.top){
			elem.style.top = "0px";
		}
		var xpos =parseInt(elem.style.left);
		var ypos = parseInt(elem.style.top);
		
		if(xpos == final_x && ypos == final_y){
			return true;
		}
		if(xpos < final_x){
			var dist = Math.ceil((final_x-xpos)/10);
			xpos = xpos+dist;
		}
		
		if(xpos > final_x){
			var dist = Math.ceil((xpos-final_x)/10);
			xpos = xpos-dist;
		}
		
		if(ypos < final_y){
			var dist = Math.ceil((final_y-ypos)/10);
			ypos=ypos+dist;
		}
		if(ypos > final_y){
			var dist = Math.ceil((ypos-final_y)/10);
			ypos=ypos-dist;
		}
		elem.style.left=xpos+"px";
		elem.style.top=ypos+"px";
		
		
		var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
		elem.movement = setTimeout(repeat,interval);
	}


 function showSection(id){
	 var sections= document.getElementsByTagName("section");
	 for(var i=0;i<sections.length;i++){
		 if(sections[i].getAttribute("id")!=id){
			 sections[i].style.display = "none";
		 }else{
			 sections[i].style.display = "block";
		 }
	 }
 }

 
 function prepareInternalnav(){
	 if(!document.getElementById) return false;
	 if(!document.getElementsByTagName)return false;
	 
	 var articles = document.getElementsByTagName("article");
	 if(articles.lenght==0) return false;
	 var navs= articles[0].getElementsByTagName("nav");
	 if(navs.length==0) return false;
	 var nav=navs[0];
	 var links = nav.getElementsByTagName("a");
	 for(var i=0;i<links.length;i++){
		 var sectionId= links[i].getAttribute("href").split("#")[1];
		 if(!document.getElementById(sectionId)) continue;
		 document.getElementById(sectionId).style.display = "none";
		 links[i].destination=sectionId;
		 links[i].onclick = function(){
			 showSection(this.destination);
			 return false;
		 };
		 
	 }
 }

 
 addLoadEvent(prepareInternalnav);
 
 
 function preparePlaceholder(){
		if(!document.getElementById || !document.createElement || !document.createTextNode) return false;
		if(!document.getElementById("imagegallery")) return false;

		var placeholder=document.createElement("img");
		placeholder.setAttribute("id", "placeholder");
		placeholder.setAttribute("src", "/JSDomDemo/images/placeholder.jpg");
		placeholder.setAttribute("alt", "my image gallery");
		placeholder.setAttribute("onload", "DrawImage(this)");
		var description = document.createElement("p");
		description.setAttribute("id", "description");
		
		var desctext= document.createTextNode("choose an image");
		description.appendChild(desctext);
		
		var gallery = document.getElementById("imagegallery");
		insertAfter(description,gallery);
		insertAfter(placeholder,description);
	}

	function showPic(whichPic){
		if(!document.getElementById("placeholder")) return false;
		var source=whichPic.getAttribute("href");
		var placeHolder=document.getElementById("placeholder");
		
		placeHolder.setAttribute("src", source);
		
		if(!document.getElementById("description")) return false;
		if(whichPic.getAttribute("title")){
			var text=whichPic.getAttribute("title");
		}else{
			var text="";
		}
		
		var description=document.getElementById("description");
		if(description.firstChild.nodeType == 3){
		description.firstChild.nodeValue=text;
		}
		return false;
		//return false;// avoid default browser active
	}


	var flag=false; 
	function DrawImage(ImgD){ 
	 var image=new Image(); 
	 var iwidth = 400;  //定义允许图片宽度 
	 var iheight = 300;  //定义允许图片高度 
	 image.src=ImgD.src; 
	 if(image.width>0 && image.height>0){ 
	 flag=true; 
	 if(image.width/image.height>= iwidth/iheight){ 
	  if(image.width>iwidth){   
	  ImgD.width=iwidth; 
	  ImgD.height=(image.height*iwidth)/image.width; 
	  }else{ 
	  ImgD.width=image.width;   
	  ImgD.height=image.height; 
	  } 
	  ImgD.alt=image.width+"×"+image.height; 
	  } 
	 else{ 
	  if(image.height>iheight){   
	  ImgD.height=iheight; 
	  ImgD.width=(image.width*iheight)/image.height;   
	  }else{ 
	  ImgD.width=image.width;   
	  ImgD.height=image.height; 
	  } 
	  ImgD.alt=image.width+"×"+image.height; 
	  } 
	 } 
	}
	 addLoadEvent(preparePlaceholder);
	 
	 function prepareGallery(){
		 if(!document.getElementById || !document.getElementsByTagName) return false;
		 if(!document.getElementById("imagegallery")) return false;
		 
		 var gallery = document.getElementById("imagegallery");
		 
		 var links=gallery.getElementsByTagName("a");
		 for(var i=0;i<links.length;i++){
			 links[i].onclick=function(){
				 return showPic(this);
			 };
		 }
	 }
	 
	 addLoadEvent(prepareGallery);
	 
	 
	 
	 function stripeTables(){
		 if(!document.getElementsByTagName) return false;
		 var tables = document.getElementsByTagName("table");
		 for(var i=0;i<tables.length;i++){
			 var odd=false;
			 var rows = tables[i].getElementsByTagName("tr");
			 for(var j=0;j<rows.length;j++){
				 if(odd == true){
					 addClass(rows[j],"odd");
					 odd=false;
				 }else{
					 odd=true;
				 }
			 }
		 }
	 }
	 
	 function highlightRows(){
		 if(!document.getElementsByTagName) return false;
		 var rows = document.getElementsByTagName("tr");
		 for(var i=0;i<rows.length;i++){
			 rows[i].oldClassName= rows[i].className;
			 rows[i].onmouseover=function(){
				 addClass(this,"highlight");
			 };
			 
			 rows[i].onmouseout = function(){
				 this.className=this.oldClassName;
			 };
		 }
	 }
	 
	addLoadEvent(stripeTables);
	addLoadEvent(highlightRows); 
	 
	 

	function focusLabels(){
		if(!document.getElementsByTagName) return false;
		
		var labels = document.getElementsByTagName("label");
		for(var i=0;i<labels.length;i++){
			if(!labels[i].getAttribute("for")) return false;
			labels[i].onclick= function() {
				var id=this.getAttribute("for");
				if(!document.getElementById(id)) return false;
				var element = document.getElementById(id);
				element.focus();
			};
		}
		
	}
	addLoadEvent(focusLabels); 
	
	function isFilled(field){
		if(field.value.replace(' ','').length == 0) return false;
		var placeholder = field.placeholder || field.getAttribute("placeholder");
		return (field.value != placeholder);
	}
	
	function isEmail(field){
		return (field.value.indexOf("@")!= -1 && field.value.indexOf(".") != -1);
	}
	
	function validateForm(whichForm){
		for(var i=0;i<whichForm.elements.length;i++){
			var element= whichForm.elements[i];
			if(element.required == 'required'){
				if(!isFilled(element)){
					alert("Please fill in the "+element.name+" field.");
					return false;
				}
			}
			if(element.type == 'email'){
				if(!isEmail(element)){
					alert("The "+element.name+" field must be a valid email address.");
					return false;
				}
			}
		}
		return true;
	}
	
	function resetFields(whichForm){
		if(Modernizr.input.placeholder) return;
		
		for(var i=0;i<whichForm.elements.length;i++){
			var element = whichForm.elements[i];
			if(element.type == 'submit') continue;
			var check = element.placeholder || element.getAttribute('placeholder');
			if(!check) continue;
            element.focus = function(){
            	var text =this.placeholder || this.getAttribute('placeholder');
            	if(this.value == text){
            		this.className='';
            		this.value="";
            	}
            };
            
            element.onblur = function(){
            	if(this.value == ""){
            		this.className = 'placeholder';
            		this.value = this.placeholder || this.getAttribute('placeholder');
            	}
            };
            element.onblur;
		}
	}
	
	function prepareForms(){
		for(var i=0;i< document.forms.length;i++){
			var thisform= document.forms[i];
			resetFields(thisform);
			thisform.onsubmit = function(){
				if(!validateForm(this)) return false;
				
				var article = document.getElementsByTagName("article")[0];
				if(submitFormWithAjax(this,article)) return false;
						
				return true;
			};
			
		}
	}
	addLoadEvent(prepareForms); 
	
	
	function getHTTPObject(){
		if(typeof XMLHttpRequest == "undefined"){
			XMLHttpRequest = function(){
				try{
					return new ActiveXObject("Msxml2.XMLHTTP.6.0");
				}catch(e){}
				try{
					return new ActiveXObject("Msxml2.XMLHTTP.3.0");
				}catch(e){}
				try{
					return new ActiveXObject("Msxml2.XMLHTTP");
				}catch(e){}
				return false;
			};
		}
		return new XMLHttpRequest();
	}
	
	
   function displayAjaxLoading(element){
	   while(element.hasChildNodes()){
		   element.removeChild(element.lastChild);
	   }
	   var content=document.createElement("img");
	   content.setAttribute("src","/JSDomDemo/images/loading.gif");
	   content.setAttribute("alt","loading......");
	   element.appendChild(content);
   }
   
   
   function submitFormWithAjax(whichform,thetarget){
	   
	   var request=getHTTPObject();
	   
	   if(!request){
		   return false;
	   }
	   displayAjaxLoading(thetarget);
	   var dataParts=[];
	   var element;
	   var und=0;
	   for(var i=0;i<whichform.elements.length;i++){
		   element =whichform.elements[i];
		   if((typeof element.name !="undefined") && element.name != ""){
		    dataParts[i-und]= element.name+ '=' + encodeURIComponent(element.value);
		   }else{
			   und++; 
		   }
	   }
	   
	   var data = dataParts.join('&');
	   request.open('POST',whichform.getAttribute("action"),true);
	   request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   
	   request.onreadystatechange= function(){
		   if(request.readyState == 4){
			   if(request.status == 200 || request.status == 0){
				   var matches =request.responseText.match(/<article>([\s\S]+)<\/article>/);
				   if(matches.length> 0){
					   thetarget.innerHTML = matches[1];
				   }else{
					   thetarget.innerHTML = '<p> Oops, there was an error, Sorry.</p>';
				   }
				   
			   }else{
				   thetarget.innerHTML ='<p>'+request.statusText+ '</p>';
			   }
		   }
	   };
	   request.send(data);
	   return true;
   }
   
   
   function prepareLoginLogout(){
	   if(!document.getElementById) return false;
	   if(document.getElementById("loginbutton")){
	   var loginbtn=document.getElementById("loginbutton");
	   loginbtn.onclick = function(){
		   window.location.href="/JSDomDemo/Login.jsp";
	   };
   	   }
	   if(document.getElementById("logoutbutton")) {
		   var logoutbtn=document.getElementById("logoutbutton");
	    logoutbtn.onclick = function(){
		   window.location.href="/JSDomDemo/Logout.jsp";
	   };
	   }
   }
   addLoadEvent(prepareLoginLogout); 